<?php
/**
 * Created by PhpStorm.
 * User: eugene
 * Date: 2018/4/4
 * Time: 09:50
 */

namespace App\Http\Controllers;


use App\Models\MyCar;
use App\Models\MyStage;
use App\Models\Stage;
use App\Repos\MemberRepo;
use App\Transformers\StageTransformer;
use Carbon\Carbon;

class StageController extends ApiController
{
    
    //获取我拥有的道具 - 弃用
    public function mine(StageTransformer $stageTransfomer)
    {
        $stages = Stage::whereHas('userHold',function($query){
            $query->where('uid',$this->user->id);
        })->paginate(20);
        
        $list = $stages->transform(function($item){
            $item['hold'] = MyStage::where('StageID',$item->StageID)->where('uid',$this->user->id)->count()?:0;
            return $item;
        });
        $list = $stageTransfomer->setTransformer('forUser')->listData($list);
    
        return $this->setPage($stages->hasMorePages())->success($list);
    }
    
    //使用道具
    public function useStage(MemberRepo $memberRepo)
    {
        $id = $this->request->stage_id;
        $unique_car_id = $this->request->car_id;
        $myCar = MyCar::findOrFail($unique_car_id);
    
        if(MyStage::where('uid',$this->user->id)->where('StageID',$id)->where('car_id',$myCar->ID)->exists()){
            return $this->error(1,'同一道具不能重复使用在同一辆车上');
        }
        
        $stage = Stage::findOrFail($id);

        //检查用户余额是否足够
        if($this->user->getCredit() < $stage->getPrice()){
            return $this->error(1,'您的余额不足以购买此道具');
        }
    
        //扣除用户余额
        $memberRepo::decrementUserCredit($this->user,$stage->getPrice());
    
        $new_stage = new MyStage();
        $new_stage->uid = $this->user->id;
        $new_stage->StageID = $id;
        $new_stage->BuyTime = Carbon::now()->toDateTimeString();
        $new_stage->car_id = $myCar->ID;
        $new_stage->save();
        
        return $this->success('使用道具成功');
    }
}